<?php

/**
 * @生成指定数量的未关联用户的二维码
 */
header('content-type:text/html;charset=utf-8');
include_once  __DIR__ . '/../Base.php';
include_once __DIR__ .'/../linhe.php';

if(isset($_GET['download'])) {
    //为下载二维码
    if(Empty($_GET['code'])) {
        echo '下载信息不正确,请核对!';
        die;
    }
    $文件路径 =G_SITE_BASE.'/cache/wxqrcode/'.$_GET['code'].'.jpg';
    下载code($文件路径,$_GET['code']);
}

function 下载code($文件路径,$文件名) {
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=".$文件名.'.jpg');
    readfile($文件路径);
}

class createcode extends Base {
    private $二维码数量;
    private $公众号id;

    public function __construct($二维码数量,$公众号id) {
        parent::__construct();

        if(Empty($二维码数量)) return false;
        if(Empty($公众号id)) return false;

        $this->二维码数量 = $二维码数量;
        $this->公众号id = $公众号id;
    }

    public function 创建指定数量的二维码() {
        $token = $this->getAccessToken($this->公众号id);
        if(Empty($token)) return false;
        $公众号openID = C公众号::ff根据公众号id查询公众号openID($this->公众号id);
        $success = 0;
        $error = 0;
        $arr = array();
        for($i=0;$i<$this->二维码数量;$i++) {
//            $二维码编号= rand('1000000','9999999').uniqid();
            $二维码编号= 'SYT'.Date(YmdHis).$i;
            $二维码信息 = $this->fc创建字符二维码($二维码编号,$token);
            $创建qrcode记录结果 = $this->创建qrcode表记录($二维码信息,$二维码编号,$公众号openID,"未关联用户的二维码");
            $创建用户二维码记录结果 = $this->创建用户二维码表记录($二维码编号,$公众号openID);
            if($二维码信息 && $创建qrcode记录结果 &&$创建用户二维码记录结果) {
//                echo '<a href="'.G_SITE_BASE.'/business/createcode.php?download=1&code='.$二维码编号.'">下载二维码_'.$二维码编号.'</a><br/><br/>';
                $arr[] = $二维码编号;
                $success+=1;
            }else {
                $error+=1;
            }
        }
//        return array('success'=>$success,'error'=>$error);
        return array('success'=>$success,'error'=>$error,'arr'=>$arr);
    }

    public function  f创建二维码($type,$id){
        $token = $this->getAccessToken($this->公众号id);
        if(Empty($token)) return false;
        $公众号openID = C公众号::ff根据公众号id查询公众号openID($this->公众号id);
        $二维码编号= $type.Date('YmdHis');
        $二维码信息 = $this->fc创建字符二维码($二维码编号,$token);
        $创建qrcode记录结果 = $this->创建qrcode表记录($二维码信息,$二维码编号,$公众号openID,"用户推广二维码",$id);
             if($二维码信息 && $创建qrcode记录结果) {
                  return $二维码编号;
            }else {
                return false;
            }
    }

    private function 创建用户二维码表记录($二维码编号,$公众号openID) {
        $do = new Do用户二维码();
        $do -> set_代理id($二维码编号);
        $do -> set_代理名称('默认收银台');
        $do -> set_二维码状态('可用');
        $do -> set_公众号ID($this->公众号id);
        $do -> set_公众号openID($公众号openID);
        $do -> set_充值状态('是');
        return $do->insert();
    }

    private function 创建qrcode表记录($二维码信息,$二维码编号,$公众号openID,$type,$用户id="") {
        $msg = $二维码信息['message'];
        $do = new DoQRcode();
        $do->set_serv_id($this->公众号id);
        $do->set_公众号ID($this->公众号id);
        $do->set_公众号openID($公众号openID);
        $do->set_user_id($用户id);
        $do->set_status(1);
        $do->set_code($二维码编号);
        $do->set_ticket($msg->ticket);
        if(isset($msg->expire_seconds))
            $do->set_expire_time($msg->expire_seconds);
        $do->set_url($msg->url);

        $do->set_image_file($二维码信息['file_name']);
        $do->set_type(1);
        $do->set_business(4);
        $do->set_note($type);
        return $do->insert();
    }
    private function fc创建字符二维码($viCodeID,$token)
    {
        $returns = array();
        $type = 'QR_LIMIT_STR_SCENE';
        $fname = Constants::e二维码_存放目录  . $viCodeID . '.jpg';
        $expire='';
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token;
        $data = '{'.$expire.' "action_name": "' . $type . '", "action_info": {"scene": {"scene_str": "' . $viCodeID . '"}}}';

        $ret1 = $this->curl_post_page($url, $data);

        if ($ret1) {
            $dt = json_decode($ret1);
            $returns['message'] = $dt;
            $ticket = $dt->ticket;
            //根据id换取二维码图片

            $ret2 = $this->curl_get_wximge($ticket);
            $returns['img'] = $ret2.'.jpg';
            $returns['file_name'] = $fname;
            $fh = fopen($fname, 'w');
            if ($fh) {
                fwrite($fh, $ret2);
                fclose($fh);
                return $returns;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private static function getAccessTokenOld($公众号ID)
    {
        $do=new DoUniversalParameters();
        $ret = pdo()->selectBO($do,array('name'=>'AccessToken','公众号ID'=>$公众号ID));
        if($ret) return $do;
        return false;
    }

    private function getAccessToken($公众号ID)
    {
        $curTime = time();
        $公众号 = pdo()->selectColumns('public_serv_accounts',array('app_id','AppSecret'),array('id'=>$公众号ID));
        $公众号appid = $公众号['app_id'];
        $公众号appsecret = $公众号['AppSecret'];

        //如果没有AccessToken记录则 从wx取得一个，并记录到数据库
        if (!$voParameters =$this->getAccessTokenOld($公众号ID)) {
            // echo "Token record not found!";

//            $newToken = $this->getAccessTokenNew($公众号appid,$公众号appsecret);
//            if (!$newToken) {
//                return false;
//            }
//            $voParameters=new DoUniversalParameters();
//            $voParameters->set_value($newToken);
//            $voParameters->set_name('AccessToken');
//            $voParameters->set_公众号ID($公众号ID);
//            $voParameters->set_公众号openID($公众号openID);
//
//            $rst = $voParameters->save();
//
//            //updated token record, current time will be updated automatically by DB
//            if ($rst)
//                return $newToken;
//            else {
//                return FALSE;
//            }
            echo '公众号不存在,请核实!';
            die;
        }

        $lastTime = strtotime($voParameters->get_update_time());
        $token = $voParameters->get_value();
        $interval = $curTime - $lastTime;

        // 小于微信规定的7200秒时间间隔，则返回当前access token，否则从微信服务器读取新的AccessToken，并记录到本地
        if ($interval < G_TOKEN_TIME) {
            return $token;
        } else {
            $newToken = $this->getAccessTokenNew($公众号appid,$公众号appsecret);
            if (!$newToken) {
                return false;
            }

            if ($this->updateToken($newToken,$公众号ID))
                return $newToken;
            else
                return FALSE;
        }
    }

    private  function getAccessTokenNew($公众号AppId,$公众号AppSecret)
    {
        $appId = $公众号AppId;
        $secret = $公众号AppSecret;

        $ret = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$secret);

        if (!$ret) {
            return false;
        }

        $decd = json_decode($ret);
        return $decd->access_token;
    }

    private function updateToken($tkRecord,$公众号ID)
    {
        if (!$tkRecord) {
            return false;
        }
        $rst = pdo()->update('UniversalParameters',['update_time'=>date('Y-m-d H:i:s',time()),'value'=>$tkRecord],['name'=>'AccessToken','公众号Id'=>$公众号ID]);

        if (!$rst) {
            return false;
        } else {
            return true;
        }
    }

    function curl_post_page($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_AUTOREFERER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $output = curl_exec($ch);
        if(curl_errno($ch)){
            echo curl_error($ch);
        }
        return $output;
    }

    function curl_get_wximge($ticket)
    {
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $pkg = curl_exec($ch);
        curl_close($ch);
        return $pkg;
    }
}

//if(Empty($_GET['num'])) echo '请填写num(二维码数量)字段值!<br/><br/>';
//if(Empty($_GET['公众号id'])) echo '请填写公众号id字段值!<br/><br/>';

//$create = new createcode($_GET['num'],$_GET['公众号id']);
//
//$result = $create ->创建指定数量的二维码();

//if($result) {
//    echo '创建成功'.$result['success'].'个二维码,创建失败'.$result['error'].'个二维码!';
//}else {
//    echo '系统error';
//}